# 有一个线上服务器访问日志, 格式如下:
# 时间                          接口              ip地址
# 2016-11-09 11:22:05     /api/usr/login      110.23.5.33
# 2016-11-09 11:23:10     /api/usr/detail     57.3.2.16
# ......
# 2016-11-09 23:59:40     /api/usr/login      200.6.5.166
# 求访问/api/usr/login接口的top10的ip地址和数量
import re

class Teacher():
    def __init__(self):
        self.li = []
        self.sli = set(self.li)
        self.dict = {}

    def parse(self,fname):
        with open(fname,"r") as f:
            # print(f.readlines())
            for line in f.readlines():
                # print(line)
                if re.search(r'/api/usr/login',line):
                    # print("----")
                    # li.append(re.search(r'\d*\.\d*\.\d*.\d*',line).group())
                    self.li.append(re.search(r'\d*\.\d*\.\d*\.\d*',line).group())

    def parse_2(self):
        self.sli = self.li
        for ip in self.sli:
            self.dict[ip]=self.li.count(ip)


    def show(self):
        dict = sorted(self.dict.items(),key=lambda x:x[1],reverse=True)
        current = 1
        for key,value in dict:
            # print("----")
            print("排名第{}的ip是{},访问次数是{}".format(current,key,value))
            current += 1

"""
测试数据log.txt

2016-11-09 11:22:05     /api/usr/login      110.23.5.33
2016-11-09 11:23:10     /api/usr/detail     57.3.2.16
2016-11-09 23:59:40     /api/usr/login      200.6.5.166
2016-11-09 23:59:40     /api/usr/login      200.6.5.166
2016-11-09 23:59:40     /api/usr/login      200.6.5.166
2016-11-09 23:59:40     /api/usr/login      200.6.5.166
2016-11-09 23:59:40     /api/usr/login      200.6.5.166
2016-11-09 23:59:40     /api/usr/login      200.6.5.166
2016-11-09 23:59:40     /api/usr/login      200.6.5.168
2016-11-09 23:59:40     /api/usr/login      200.6.5.168
2016-11-09 23:59:40     /api/usr/login      200.6.5.168
2016-11-09 23:59:40     /api/usr/login      200.6.5.166
2016-11-09 23:59:40     /api/usr/login      200.6.5.167
2016-11-09 23:59:40     /api/usr/login      200.6.5.167
"""
if __name__ == '__main__':
    teacher=Teacher()
    teacher.parse('log.txt')
    teacher.parse_2()
    teacher.show()
